package com.hgw.easyrocketmq.order.producer;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.remoting.exception.RemotingException;

import java.util.ArrayList;
import java.util.List;

/**
 * Description: 发送顺序消息
 *
 * @author LinHuiBa-YanAn
 * @date 2023/1/14 14:21
 */
public class OrderProducer {

	public static void main(String[] args) throws MQClientException, RemotingException, InterruptedException, MQBrokerException {
		DefaultMQProducer mqProducer = new DefaultMQProducer("group1");
		mqProducer.setNamesrvAddr("124.222.223.222:9876;47.96.232.192:9876");
		mqProducer.start();
		// 订单列表
		List<OrderStep> orderList = new OrderProducer().buildOrders();

		for (int i = 0; i < orderList.size(); i++) {
			String body = orderList.get(i).toString();
			Message msg = new Message("orderTopic", "Order", "KEY" + i, body.getBytes());
			/**
			 * Params:
			 *  - 消息对象
			 *  - 消息队列的选择器
			 *  - 选择队列的业务标识（订单ID）
			 */
			SendResult sendResult = mqProducer.send(msg, new MessageQueueSelector() {
				/**
				 * 选择指定的队列发送消息
				 * @param mqs 队列的集合
				 * @param msg 消息对象
				 * @param arg 业务标识的参数
				 * @return
				 */
				@Override
				public MessageQueue select(List<MessageQueue> mqs, Message msg, Object arg) {
					long orderId = (long) arg;
					int index = (int) (orderId % mqs.size());
					return mqs.get(index);
				}
			}, orderList.get(i).getOrderId());
			System.out.println("发送结果：" + sendResult);
		}
		mqProducer.shutdown();
	}

	/**
	 * 生成模拟订单数据
	 */
	private List<OrderStep> buildOrders() {
		List<OrderStep> orderList = new ArrayList<>();
		orderList.add(new OrderStep(100001L, "创建"));
		orderList.add(new OrderStep(100002L, "创建"));
		orderList.add(new OrderStep(100001L, "付款"));
		orderList.add(new OrderStep(100003L, "创建"));
		orderList.add(new OrderStep(100002L, "付款"));
		orderList.add(new OrderStep(100003L, "付款"));
		orderList.add(new OrderStep(100002L, "完成"));
		orderList.add(new OrderStep(100001L, "推送"));
		orderList.add(new OrderStep(100003L, "完成"));
		orderList.add(new OrderStep(100001L, "完成"));
		return orderList;
	}

	/**
	 * 订单的步骤
	 */
	@Data
	@AllArgsConstructor
	@NoArgsConstructor
	private static class OrderStep {
		private long orderId;
		private String desc;

		@Override
		public String toString() {
			return "OrderStep{" +
					"orderId=" + orderId +
					", desc='" + desc + '\'' +
					'}';
		}
	}
}
